package whf.framework.ext.service;

import java.util.List;

import whf.framework.exception.FindException;
import whf.framework.exception.RemoveException;
import whf.framework.exception.ServiceNotFoundException;
import whf.framework.ext.dao.CategoryDAO;
import whf.framework.ext.dao.DictItemDAO;
import whf.framework.ext.entity.Category;
import whf.framework.ext.entity.DictItem;
import whf.framework.util.BeanFactory;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-06-16
 */
public class CategoryServiceImp extends whf.framework.service.ServiceImp<Category> implements CategoryService {

	private CategoryDAO categoryDAO;
	
	private DictItemDAO dictItemDAO;

	public void setCategoryDAO(CategoryDAO categoryDAO) {
		this.categoryDAO = categoryDAO;
	}
	
	public void setDictItemDAO(DictItemDAO dao) {
		this.dictItemDAO = dao;
	}

	public static CategoryService getCategoryService() throws ServiceNotFoundException {
		return (CategoryService)BeanFactory.getService(CategoryServiceImp.class) ;
	}

	public List<Category> findCategories(Category parent) throws FindException {
		return categoryDAO.findCategories(parent);
	}
	
	public Category findByCode(String code) throws FindException{
		List<Category> list = this.categoryDAO.find("t.code=?", code);
		if(list.size() > 0){
			return list.get(0);
		} else {
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see whf.framework.ext.service.CategoryService#findByEnumClassName(java.lang.String)
	 */
	public Category findByEnumClassName(String enumClassName) throws FindException {
		List<Category> list = this.categoryDAO.find("t.enumClassName=?", enumClassName);
		if(list.size() > 0){
			return list.get(0);
		} else {
			return null;
		}
	}

	@Override
	public void remove(Category entity) throws RemoveException {
		try{
			List<DictItem> items = this.dictItemDAO.findByCategory(entity);
			for(DictItem item: items) {
				this.dictItemDAO.remove(item);
			}
		}catch(FindException e){
			throw new RemoveException(e);
		}
		super.remove(entity);
	}

} 